package chooongg.base.widget.hText

import android.animation.Animator
import android.graphics.Canvas
import android.util.AttributeSet
import java.util.*

interface AnimationListener {
    fun onAnimationEnd(mHTextView: HTextView?)
}

data class CharacterDiffResult(
    var c: Char,
    var fromIndex: Int,
    var moveIndex: Int
)

object CharacterUtils {
    fun diff(oldText: CharSequence, newText: CharSequence): List<CharacterDiffResult> {
        val differentList: MutableList<CharacterDiffResult> = ArrayList()
        val skip: MutableSet<Int> = HashSet()
        for (i in oldText.indices) {
            val c = oldText[i]
            for (j in newText.indices) {
                if (!skip.contains(j) && c == newText[j]) {
                    skip.add(j)
                    val different = CharacterDiffResult(c, i, j)
                    differentList.add(different)
                    break
                }
            }
        }
        return differentList
    }

    fun needMove(index: Int, differentList: List<CharacterDiffResult>): Int {
        for ((_, fromIndex, moveIndex) in differentList) {
            if (fromIndex == index) {
                return moveIndex
            }
        }
        return -1
    }

    fun stayHere(index: Int, differentList: List<CharacterDiffResult>): Boolean {
        for ((_, _, moveIndex) in differentList) {
            if (moveIndex == index) {
                return true
            }
        }
        return false
    }

    fun getOffset(
        from: Int, move: Int, progress: Float, startX: Float, oldStartX: Float,
        gaps: List<Float>, oldGaps: List<Float>
    ): Float {
        var dist = startX
        for (i in 0 until move) {
            dist += gaps[i]
        }
        var cur = oldStartX
        for (i in 0 until from) {
            cur += oldGaps[i]
        }
        return cur + (dist - cur) * progress
    }
}

open class DefaultAnimatorListener : Animator.AnimatorListener {
    override fun onAnimationStart(animation: Animator) = Unit
    override fun onAnimationEnd(animation: Animator) = Unit
    override fun onAnimationCancel(animation: Animator) = Unit
    override fun onAnimationRepeat(animation: Animator) = Unit
}

interface IHText {
    fun init(
        hTextView: HTextView?,
        attrs: AttributeSet?,
        defStyle: Int
    )

    fun animateText(text: CharSequence?)
    fun onDraw(canvas: Canvas?)
    fun setAnimationListener(listener: AnimationListener?)
}